<script>
    import { MESSAGE_TYPE } from 'vue-baberrage'

    export default {
        name: 'danmu',
        data () {
            return {
                msg: '你好，学院君！',
                position: 'top',
                barrageIsShow: true,
                currentId: 0,
                barrageLoop: true,
                websocket: null,
                barrageList: []
            }
        },
        created () {
            // 初始化 websocket 并定义回调函数
            this.websocket = new WebSocket("ws://laravel58.test/ws/");
            this.websocket.onopen = function (event) {
                console.log("已建立 WebSocket 连接");
            };
            let that = this;
            this.websocket.onmessage = function (event) {
                // 接收到 WebSocket 服务器返回消息时触发
                let data = JSON.parse(event.data);
                that.addToList(data.position, data.message);
            };
            this.websocket.onerror = function (event) {
                console.log("与 WebSocket 通信出错");
            };
            this.websocket.onclose = function (event) {
                console.log("断开 WebSocket 连接");
            };
        },
        destroyed () {
            this.websocket.close();
        },
        methods: {
            removeList () {
                this.barrageList = []
            },
            addToList (position, message) {
                if (position === 'top') {
                    this.barrageList.push({
                        id: ++this.currentId,
                        avatar: 'https://xueyuanjun.com/assets/avatars/numxwdxf8lrtrsol.jpg',
                        msg: message,
                        barrageStyle: 'top',
                        time: 8,
                        type: MESSAGE_TYPE.FROM_TOP,
                        position: 'top'
                    })
                } else {
                    this.barrageList.push({
                        id: ++this.currentId,
                        avatar: 'https://xueyuanjun.com/assets/avatars/numxwdxf8lrtrsol.jpg',
                        msg: message,
                        time: 15,
                        type: MESSAGE_TYPE.NORMAL
                    })
                }
            },
            sendMsg () {
                // 发送消息到 WebSocket 服务器
                this.websocket.send('{"position":"' + this.position + '", "message":"' + this.msg + '"}');
            },
        }
    }
</script>
